<script setup lang="ts">
defineOptions({name:'User'})
import {ref, onMounted, reactive, nextTick} from "vue";
import {reqUserInfo, reqAddOrUpdateUser, reqAllRole, reqSetRole,reqRemoveUser,reqRemoveUsers} from '@/api/acl/user/index.ts'
import type {UserResponseData,User,AllRoleResponseData,AllRole,SetRoleData} from '@/api/acl/user/type.ts'
import {ElMessage} from "element-plus";
import useLayOutSettingStore  from "@/store/modules/setting.ts";

const pageNo=ref<number>(1)
const pageSize=ref<number>(5)
const total=ref<number>(0)
const userArr = ref<User[]>([])
/**
 * 获取用户信息
 * @param pager
 */
const getUserInfo = async (pager=1) => {
  pageNo.value=pager
  const res:UserResponseData = await reqUserInfo(pageNo.value,pageSize.value,keyWord.value)
  if(res.code==200){
    total.value=res.data.total
    userArr.value=res.data.records
  }
  // console.log(res)
}
/**
 * 改变每页数量
 */
const changePageSize = () => {
  getUserInfo()
}
onMounted(()=>{
  getUserInfo()
})
//编辑用户信息抽屉的显示控制
const drawerShow = ref<boolean>(false)
//手机用户信息
const userParams = reactive<User>({
  id:'',
  createTime: '',
  updateTime: '',
  username: '',
  password: '',
  name:'',
  phone: '',
  roleName: '',
})
//form实例
const formRef = ref<any>()
/**
 * 编辑用户信息
 * @param row
 */
const editUserInfo = (row:User) => {
  // console.log(row)
  drawerShow.value=true
  nextTick(() => {
    formRef.value?.clearValidate('username')
    formRef.value?.clearValidate('password')
    formRef.value?.clearValidate('name')
  })
  if(row.id){
    Object.assign(userParams,row)
  }else {
    Object.assign(userParams,{id:'', username: '', password: '', name:''})
  }
}
/**
 * 完成修改
 */
const save = async () => {
  const verifyRes=await formRef.value?.validate()
  if(!verifyRes) return
  const res:any = await reqAddOrUpdateUser(userParams)
  // console.log(res)
  if(res.code==200){
    drawerShow.value=false
    ElMessage({type:'success',message:userParams.id?'更新成功':'添加成功'})
    await getUserInfo(userParams.id?pageNo.value:pageNo.value-1)
    //浏览器自动刷新
    window.location.reload()
  }else{
    drawerShow.value=false
    ElMessage({type:'error',message:userParams.id?'更新失败':'添加失败'})
  }
}
/**
 * 用户名校验
 * @param rule
 * @param value
 * @param callBack
 */
const validateUsername = (_:any,value:any,callBack:any) => {
  if(value.trim().length>=5){
    callBack()
  }else {
    callBack(new Error('用户名字符长度有误'))
  }
}
/**
 *昵称校验
 * @param rule
 * @param value
 * @param callBack
 */
const validateName = (_:any,value:any,callBack:any) => {
  if(value.trim().length>=5){
    callBack()
  }else {
    callBack(new Error('昵称字符长度有误'))
  }
}
/**
 *密码校验
 * @param rule
 * @param value
 * @param callBack
 */
const validatePassword = (_:any,value:any,callBack:any) => {
  if(value.trim().length>=6){
    callBack()
  }else {
    callBack(new Error('密码字符长度有误'))
  }
}
//规则
const rules={
  username:[{required:true,trigger:'blur',validator:validateUsername}],
  name:[{required:true,trigger:'blur',validator:validateName}],
  password:[{required:true,trigger:'blur',validator:validatePassword}]
}
//职位抽屉显示控制
const positionDrawerShow=ref<boolean>(false)
//所有职位
const allRole = ref<AllRole>([])
//当前职位
const userRole = ref<AllRole>([])
/**
 * 设置角色
 */
const setRole = async (row:User) => {
  // console.log(row)
  positionDrawerShow.value=true
  Object.assign(userParams,row)
  const res:AllRoleResponseData = await reqAllRole(row.id as number)
  if(res.code==200){
    allRole.value = res.data.allRolesList
    userRole.value = res.data.assignRoles
  }
  // console.log(res)
}
//是否全选
const checkAll=ref<boolean>(false)
// 全选的小图标
const isIndeterminate = ref<boolean>(true)
/**
 * 点击全选触发
 */
const handleCheckAllChange = (val:boolean) => {
  userRole.value = val?allRole.value:[]
  isIndeterminate.value=false
}
/**
 * 收集到的已选值数组
 * @param val
 */
const handleCheckedRolesChange = (val:any) => {
  isIndeterminate.value=(!allRole.value.length===val.length)
  checkAll.value= allRole.value.length==val.length
}
/**
 * 设置职位
 */
const saveRole = async () => {
  const data:SetRoleData={
    userId:(userParams.id as number),
    roleIdList:userRole.value.map((item:any)=>item.id as number)
  }
  const res:any= await reqSetRole(data)
  if(res.code==200){
    await getUserInfo(pageNo.value)
    ElMessage({type:'success',message:'分配职务成功'})
    positionDrawerShow.value=false
  }
}
/**
 * 删除用户
 * @param userId
 */
const deleteUser = async (userId:number) => {
  const res:any = await reqRemoveUser(userId)
  if(res.code==200){
    ElMessage({type:'success',message:'删除用户成功'})
    await getUserInfo(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
  }else{
    ElMessage({type:'error',message:'删除用户失败'})
  }
  // console.log(res)
}
// 存储多个用户ID的数组
const selectIdArr = ref<number[]>([])
/**
 * 勾选表格选项时触发
 * @param userInfo
 */
const selectChange = (userInfo: any) => {
  selectIdArr.value=userInfo
  console.log(selectIdArr.value)
}
/**
 * 删除选中用户
 */
const deleteSelectUser = async () => {
  selectIdArr.value=selectIdArr.value.map((item:any)=>item.id)
  const res:any = await reqRemoveUsers(selectIdArr.value)
  if(res.code==200){
    ElMessage({type:'success',message:'批量删除用户成功'})
    await getUserInfo()
  }else{
    ElMessage({type:'error',message:'批量删除用户失败'})
  }
}
// 定义搜索关键字
const keyWord = ref<string>('')
/**
 * 搜索功能
 */
const search = () => {
  getUserInfo()
  keyWord.value=''
}
const layOutSettingStore = useLayOutSettingStore()
/**
 * 刷新页面
 */
const reset = () => {
  layOutSettingStore.refresh=!layOutSettingStore.refresh
}
</script>
<template>
  <el-card>
    <el-form inline class="form">
      <el-form-item label="用户名：">
        <el-input placeholder="请你输入搜索的用户名字" v-model="keyWord"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :disabled="!keyWord" @click="search">搜索</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin-top: 10px;">
    <el-button type="primary" @click="editUserInfo">添加用户</el-button>
    <el-button type="danger" :disabled="!(selectIdArr.length>0)" @click="deleteSelectUser">批量删除</el-button>
    <el-table border style="margin-top: 10px;" :data="userArr" @selection-change="selectChange">
      <el-table-column type="selection" align="center" ></el-table-column>
      <el-table-column type="index" align="center" ></el-table-column>
      <el-table-column label="ID" align="center" prop="id"></el-table-column>
      <el-table-column label="用户名字" align="center" prop="username"></el-table-column>
      <el-table-column label="用户名称" align="center" prop="name"></el-table-column>
      <el-table-column label="用户角色" align="center" prop="roleName" show-overflow-tooltip></el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime"></el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime"></el-table-column>
      <el-table-column label="操作" width="320px" align="center">
        <template #default="{row}">
          <el-button icon="User" type="primary" size="small" @click="setRole(row)">分配角色</el-button>
          <el-button icon="Edit" type="success" size="small" @click="editUserInfo(row)">编辑</el-button>
          <el-popconfirm :title="`您确定要删除${row.username}吗?`" @confirm="deleteUser(row.id)">
            <template #reference>
              <el-button icon="Delete" type="danger" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[5,7,9,11]"
        :disabled="false"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        style="margin-top: 15px"
        @current-change="getUserInfo"
        @size-change="changePageSize"
    />
  </el-card>
<!--  编辑用户信息-->
  <el-drawer v-model="drawerShow">
    <template #header>
      <h4>{{userParams.id?'编辑':'添加'}}用户信息</h4>
    </template>
    <template #default>
      <el-form :model="userParams" :rules="rules" ref="formRef">
        <el-form-item label="用户姓名：" prop="username">
          <el-input placeholder="请您输入用户名：" v-model="userParams.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称：" prop="name">
          <el-input placeholder="请您输入昵称：" v-model="userParams.name"></el-input>
        </el-form-item>
        <el-form-item label="用户密码：" prop="password" v-if="userParams.id===''">
          <el-input placeholder="请您输入用户密码：" v-model="userParams.password"></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawerShow=false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </template>
  </el-drawer>
<!--  编辑职位信息-->
  <el-drawer v-model="positionDrawerShow">
    <template #header>
      用户角色分配
    </template>
    <template #default>
      <el-form label-width="110px">
        <el-form-item label="用户姓名：" >
          <el-input v-model="userParams.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="职位列表：">
          <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
              style="margin-right: 300px;"
          >全选
          </el-checkbox>
          <el-checkbox-group
              v-model="userRole"
              @change="handleCheckedRolesChange"
          >
            <el-checkbox v-for="role in allRole" :key="role.id" :label="role">{{role.roleName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="positionDrawerShow=false">取消</el-button>
        <el-button type="primary" @click="saveRole">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<style scoped lang="scss">
.form{
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>